import { Card, Form, Input, Button, message, Avatar, Upload, Space, Divider } from 'antd'
import { useState, useEffect } from 'react'
import { useUserStore } from '../../store/user'
import './AccountSettings.css'
import {
    UserOutlined,
    LockOutlined,
    MailOutlined,
    PhoneOutlined,
    CameraOutlined,
    SaveOutlined,
    EyeInvisibleOutlined,
    EyeTwoTone
} from '@ant-design/icons'

export default function AccountSettings() {
    const [profileForm] = Form.useForm()
    const [passwordForm] = Form.useForm()
    const { user, login } = useUserStore()
    const [profileLoading, setProfileLoading] = useState(false)
    const [passwordLoading, setPasswordLoading] = useState(false)
    const [avatarUrl, setAvatarUrl] = useState('')

    useEffect(() => {
        if (user) {
            profileForm.setFieldsValue({
                userName: user.userName,
                userAccount: user.userAccount,
                email: user.email,
                phone: user.phone,
                userProfile: user.userProfile
            })
            setAvatarUrl(user.userAvatar || '')
        }
    }, [user, profileForm])

    const handleProfileUpdate = async (values) => {
        setProfileLoading(true)
        try {
            // 这里应该调用API更新用户信息
            // const response = await updateUserProfile(values)
            
            // 模拟API调用
            const updatedUser = {
                ...user,
                ...values,
                userAvatar: avatarUrl
            }
            login(updatedUser)
            message.success('个人信息更新成功')
        } catch (error) {
            message.error('更新个人信息失败')
        } finally {
            setProfileLoading(false)
        }
    }

    const handlePasswordChange = async (values) => {
        setPasswordLoading(true)
        try {
            // 这里应该调用API修改密码
            // await changePassword(values)
            
            message.success('密码修改成功')
            passwordForm.resetFields()
        } catch (error) {
            message.error('密码修改失败')
        } finally {
            setPasswordLoading(false)
        }
    }

    const handleAvatarChange = (info) => {
        if (info.file.status === 'uploading') {
            return
        }
        if (info.file.status === 'done') {
            // 获取上传后的URL
            const url = info.file.response?.url || URL.createObjectURL(info.file.originFileObj)
            setAvatarUrl(url)
            message.success('头像上传成功')
        } else if (info.file.status === 'error') {
            message.error('头像上传失败')
        }
    }

    const beforeUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isJpgOrPng) {
            message.error('只能上传 JPG/PNG 格式的图片!')
            return false
        }
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
            message.error('图片大小不能超过 2MB!')
            return false
        }
        return true
    }

    const uploadButton = (
        <div>
            <CameraOutlined />
            <div style={{ marginTop: 8 }}>上传头像</div>
        </div>
    )

    return (
        <div className="account-settings">
            <div className="settings-header">
                <h1 className="settings-title">
                    <UserOutlined />
                    账号设置
                </h1>
                <p className="settings-subtitle">管理您的个人信息和账号安全</p>
            </div>

            <div className="settings-content">
                {/* 个人信息设置 */}
                <Card 
                    title={
                        <Space>
                            <UserOutlined />
                            个人信息
                        </Space>
                    }
                    className="settings-card"
                >
                    <Form
                        form={profileForm}
                        layout="vertical"
                        onFinish={handleProfileUpdate}
                        className="profile-form"
                    >
                        <div className="avatar-section">
                            <div className="avatar-container">
                                <Avatar 
                                    size={100} 
                                    src={avatarUrl} 
                                    icon={<UserOutlined />}
                                    className="user-avatar"
                                />
                                <Upload
                                    name="avatar"
                                    listType="picture-card"
                                    className="avatar-uploader"
                                    showUploadList={false}
                                    action="/api/upload/avatar"
                                    beforeUpload={beforeUpload}
                                    onChange={handleAvatarChange}
                                >
                                    <Button 
                                        type="text" 
                                        icon={<CameraOutlined />}
                                        className="avatar-upload-btn"
                                    >
                                        更换头像
                                    </Button>
                                </Upload>
                            </div>
                        </div>

                        <Form.Item
                            label="用户名"
                            name="userName"
                            rules={[{ required: true, message: '请输入用户名' }]}
                        >
                            <Input prefix={<UserOutlined />} placeholder="请输入用户名" />
                        </Form.Item>

                        <Form.Item
                            label="账号"
                            name="userAccount"
                        >
                            <Input prefix={<UserOutlined />} disabled />
                        </Form.Item>

                        <Form.Item
                            label="邮箱"
                            name="email"
                            rules={[
                                { type: 'email', message: '请输入有效的邮箱地址' }
                            ]}
                        >
                            <Input prefix={<MailOutlined />} placeholder="请输入邮箱" />
                        </Form.Item>

                        <Form.Item
                            label="手机号"
                            name="phone"
                            rules={[
                                { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }
                            ]}
                        >
                            <Input prefix={<PhoneOutlined />} placeholder="请输入手机号" />
                        </Form.Item>

                        <Form.Item
                            label="个人简介"
                            name="userProfile"
                        >
                            <Input.TextArea 
                                rows={4} 
                                placeholder="请输入个人简介" 
                                maxLength={200}
                                showCount
                            />
                        </Form.Item>

                        <Form.Item>
                            <Button 
                                type="primary" 
                                htmlType="submit" 
                                loading={profileLoading}
                                icon={<SaveOutlined />}
                                block
                            >
                                保存个人信息
                            </Button>
                        </Form.Item>
                    </Form>
                </Card>

                {/* 密码修改 */}
                <Card 
                    title={
                        <Space>
                            <LockOutlined />
                            修改密码
                        </Space>
                    }
                    className="settings-card"
                >
                    <Form
                        form={passwordForm}
                        layout="vertical"
                        onFinish={handlePasswordChange}
                        className="password-form"
                    >
                        <Form.Item
                            label="当前密码"
                            name="currentPassword"
                            rules={[{ required: true, message: '请输入当前密码' }]}
                        >
                            <Input.Password 
                                prefix={<LockOutlined />}
                                placeholder="请输入当前密码"
                                iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                            />
                        </Form.Item>

                        <Form.Item
                            label="新密码"
                            name="newPassword"
                            rules={[
                                { required: true, message: '请输入新密码' },
                                { min: 6, message: '密码长度至少6位' }
                            ]}
                        >
                            <Input.Password 
                                prefix={<LockOutlined />}
                                placeholder="请输入新密码"
                                iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                            />
                        </Form.Item>

                        <Form.Item
                            label="确认新密码"
                            name="confirmPassword"
                            dependencies={['newPassword']}
                            rules={[
                                { required: true, message: '请确认新密码' },
                                ({ getFieldValue }) => ({
                                    validator(_, value) {
                                        if (!value || getFieldValue('newPassword') === value) {
                                            return Promise.resolve()
                                        }
                                        return Promise.reject(new Error('两次输入的密码不一致'))
                                    },
                                }),
                            ]}
                        >
                            <Input.Password 
                                prefix={<LockOutlined />}
                                placeholder="请确认新密码"
                                iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                            />
                        </Form.Item>

                        <Form.Item>
                            <Button 
                                type="primary" 
                                htmlType="submit" 
                                loading={passwordLoading}
                                icon={<LockOutlined />}
                                block
                                danger
                            >
                                修改密码
                            </Button>
                        </Form.Item>
                    </Form>
                </Card>
            </div>
        </div>
    )
}
